#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <fcntl.h>
#include <errno.h>
#include <time.h>
#include <linux/input.h>
#include <sys/ioctl.h>

#define LED2_MAGIC 'L'
#define LED3_MAGIC 'M'
#define LED4_MAGIC 'N'
#define LED5_MAGIC 'O'

#define LED2_ON	_IOW(LED2_MAGIC, 0, int)
#define LED2_OFF	_IOW(LED2_MAGIC, 1, int)
#define LED3_ON	_IOW(LED3_MAGIC, 0, int)
#define LED3_OFF	_IOW(LED3_MAGIC, 1, int)
#define LED4_ON	_IOW(LED4_MAGIC, 0, int)
#define LED4_OFF	_IOW(LED4_MAGIC, 1, int)
#define LED5_ON	_IOW(LED5_MAGIC, 0, int)
#define LED5_OFF	_IOW(LED5_MAGIC, 1, int)
#define INPUT_NAME "Keyboard"

void led_ctl(int i)
{
	int fd;
	int timer = 50; //10 -> 2.5s
	long unsigned int tmp_on ;
	long unsigned int tmp_off ;
	fd = open("/dev/led0", O_RDWR);
	if (fd < 0) {
		perror("open");
		exit(1);
	}
	switch(i)
	{
		case 2:
			tmp_on = LED2_ON;
			tmp_off = LED2_OFF;
			break;
		case 3:
			tmp_on = LED3_ON;
			tmp_off = LED3_OFF;
			break;
		case 4:
			tmp_on = LED4_ON;
			tmp_off = LED4_OFF;
			break;
		case 5:
			tmp_on = LED5_ON;
			tmp_off = LED5_OFF;
			break;
	}
	while(timer--)
	{
		ioctl(fd, tmp_on);
		usleep(100000);
		ioctl(fd, tmp_off);
		usleep(100000);
	}
	return ;
}
char str[256] = {0};
const char chr_table[129] = {
	[0] = '\0', [1] = '*', [2] = '1', [3] = '2', [4] = '3', 
	[5] = '4', [6] = '5', [7] = '6', [8] = '7', [9] = '8',
	[10] = '9',[11] = '0', [12] = '-', [13] = '=', [14] = '\b', 
	[15] = '\t', [16] = 'q', [17] = 'w', [18] = 'e', [19] = 'r',
	[20] = 't', [21] = 'y', [22] = 'u', [23] = 'i', [24] = 'o', 
	[25] = 'p', [26] = '{', [27] = '}', [28] = '\n', [29] = '*',
	[30] = 'a', [31] = 's', [32] = 'd', [33] = 'f', [34] = 'g', 
	[35] = 'h', [36] = 'j', [37] = 'k', [38] = 'l', [39] = ':',
	[40] = '"', [41] = '*', [42] = '*', [43] = '\\',
	[44] = 'z', [45] = 'x', [46] = 'c', [47] = 'v', [48] = 'b', 
	[49] = 'n', [50] = 'm', [51] = ',', [52] = '.', [53] = '/', 
	[54] = '*', [55] = '*', [56] = '*', [57] = ' ', [58] = '*', 
	[59] = '*', [60] = '*', [61] = '*', [62] = '*', [63] = '*',
	[64] = '*', [65] = '*', [66] = '*', [67] = '*', [68] = '*', 
	[69] = '*', [70] = '*', [71] = '*', [72] = '*', [73] = '*',
	[74] = '*', [75] = '*', [76] = '*', [77] = '*', [78] = '*', [79] = '*',
	[80] = '*', [81] = '*', [82] = '*', [83] = '*', [84] = '*',
	[85] = '*', [86] = '*', [87] = '*', [88] = '*', [89] = '*', [90] = '*', 
	[91] = '*', [92] = '*', [93] = '*', [94] = '*', [95] = '*', 
	[96] = '*', [97] = '*', [98] = '*', [99] = '*', [100] = '*', 
	[101] = '*', [102] = '*', [103] = '*', [104] = '*', [105] = '*',
	[106] = '*', [107] = '*', [108] = '*',[109] = '*', [110] = '*',
	[111] = '*', [112] = '*', [113] = '*', [114] = '*', [115] = '*',
	[116] = '*', [117] = '*', [118] = '*', [119] = '*', [120] = '*',
	[121] = '*', [122] = '*', [123] = '*', [124] = '*', [125] = '*', 
	[126] = '*', [127] = '*', [128] = '*'
};


static int open_input( const char *input_name )
{
    char name[64];
    char buf[128];
    int fd, flags;
    int i = 0;
    for (i = 0; i < 32; i++) {
        sprintf(name, "/dev/input/event%d", i );
        if( access( name, F_OK ) != 0 )
            continue;
        if ((fd = open(name, O_RDONLY, 0)) >= 0) {
             ioctl(fd, EVIOCGNAME(sizeof(buf)), buf);
             printf("name:%s \r\n", buf );
             if( strstr( buf, input_name ) == NULL )
             {
                 close( fd );
                 continue;
             }
            flags = fcntl(fd,F_GETFL,0);  
            flags |= O_NONBLOCK;  
            if( 0 != fcntl(fd,F_SETFL,flags) )
                printf("fcntl failed!:%s \r\n", strerror( errno ));
            printf("open for device:%s \r\n", name );
            return fd;
        }
    }
    return -1;
}

static int input_ready( int fd, int tout )
{
    fd_set  rfd_set;
    struct  timeval tv, *ptv;
    int nsel;

    FD_ZERO( &rfd_set );
    FD_SET( fd, &rfd_set );
    if ( tout == -1 )
    {   
        ptv = NULL;
    }
    else
    {
        tv.tv_sec = 0;
        tv.tv_usec = tout * 1000;
        ptv = &tv;
    }
    nsel = select( fd+1, &rfd_set, NULL, NULL, ptv );
    if ( nsel > 0 && FD_ISSET( fd, &rfd_set ) ) 
        return 1;
    return 0;
}

static int read_input( int fd, char *buf , int maxsize )
{
    struct input_event event;
    int rc;
    int n = 0;
    char *ptr = buf;
    char ch;
    int index;
    int last_key;
    do{
        if( (rc = read(fd, &event, sizeof(event))) < 0)
            return -1;
        if( event.type == EV_KEY && event.value == 1 )
        {
            index = event.code & 0xff;
            if( index  == 42 )
            {
                last_key = 42;
                continue;
            }
            if( index < 128 )
            {
                ch = chr_table[index];
                if( ch != 0 && ch != '*' )
                {
                    // shift key then a -> 'A'
                    if( last_key == 42 )
                        *ptr++ = ch - ( 'a' - 'A' );
                    else
                        *ptr++ = ch;
                    last_key = 0;
                    n++;
                }
            }
        }
    }while( input_ready( fd, 200 ) > 0 && n < maxsize );
    *ptr = '\0';
    return n;
}

int main( int argc, char *argv[] )
{
    int fd = -1;
    int bRun = 1;
    char buffer[256];
    int len;
    while( bRun )
    {
		buffer[0] = '\0';
        if( fd < 0 )
        {
            //try to open input dev
            fd  = open_input( INPUT_NAME );
            if( fd < 0 )
            {
                printf("无输入设备可打开！\r\n");
               // sleep( 10 );
                //continue;
				return -1;
            }
            printf("设备打开成功，开始接收数据...\r\n");
        }
        if( input_ready( fd, 200 ) > 0 )
        {
            len = read_input( fd, buffer, sizeof( buffer ));
            if( len < 0 )
            {
                printf("设备已断开！，关闭！\r\n");
                fd = -1;
                continue;
            }
        }
		if(0 == strcmp(buffer,"\n"))
		{
			break;
		}
		if(buffer[0] != '\0')
		{
			strcat(str,buffer);
		    printf("READ:%s \r\n", buffer);
		}
		if(0 == strcmp(buffer,"a"))
		{
			led_ctl(2);
		}
		if(0 == strcmp(buffer,"b"))
		{
			led_ctl(3);
		}
		if(0 == strcmp(buffer,"c"))
		{
			led_ctl(4);
		}
		if(0 == strcmp(buffer,"d"))
		{
			led_ctl(5);
		}
    }
	printf("str = %s \r\n",str);
	return 0;
}
